package com.zhsj.OkeHomeConsumption.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.TabLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.header.BezierRadarHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.zhsj.OkeHomeConsumption.R;
import com.zhsj.OkeHomeConsumption.common.Constants;
import com.zhsj.OkeHomeConsumption.common.MyActivity;
import com.zhsj.OkeHomeConsumption.empty.DealListBean;
import com.zhsj.OkeHomeConsumption.ui.activity.mvp.DealListPresenter;
import com.zhsj.OkeHomeConsumption.ui.activity.mvp.DealListUIInterFace;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;

//会员--交易订单
public class UserBlancleActivity extends MyActivity implements DealListUIInterFace {

    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.tl_main)
    TabLayout tablayout;
    private RecyclerView user_recycleview;
    private DealListPresenter dealListPresenter;
    private ArrayList<DealListBean> dealListBeans;
    private ArrayList<DealListBean> dealListBeanLists;
    private DealListAdapter dealListAdapter;
    private int pageIndex = 1;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_user_blancle;
    }

    @Override
    protected int getTitleId() {
        return R.id.userblance_titile;
    }

    public void initView() {
        dealListPresenter = new DealListPresenter(getActivity(), this);
        user_recycleview = (RecyclerView) findViewById(R.id.user_recycleview);
        dealListBeans = new ArrayList<>();
        dealListBeanLists = new ArrayList<>();
        refreshLayout.setEnableRefresh(false);//是否启用下拉刷新功能
        LinearLayoutManager manager = new LinearLayoutManager(this);
        user_recycleview.setLayoutManager(manager);
        String []mTitles = {"全部订单", "待付款", "待使用","已完成","已取消"};
        for (int i = 0; i < mTitles.length; i++) {
            tablayout.addTab(tablayout.newTab().setText(mTitles[i]));
        }
    }

    @Override
    protected void initData() {
        //设置 Header 为 贝塞尔雷达 样式
        refreshLayout.setRefreshHeader(new BezierRadarHeader(this).setEnableHorizontalDrag(true));
        dealListPresenter.UserBlanceListPost(1,0);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                refreshlayout.finishRefresh(2000);//传入false表示刷新失败
//                if (orderBeanList != null && orderBeanList.size() > 0) {
//                    orderBeanList.clear();
//                }
//                refreshLayout.setRefreshing(false);
                initRefersh();
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                refreshlayout.finishLoadMore(2000/*,false*/);//传入false表示加载失败
                NextPost();
            }
        });

    }

    public void initRefersh() {
        pageIndex = 1;
        dealListBeanLists.clear();
        dealListPresenter.UserBlanceListPost(1,0);
    }

    public void NextPost() {
        pageIndex++;
        dealListPresenter.UserBlanceListPost(pageIndex,0);
    }

    @Override
    public void UserBlanceListPost(String context) {
        try {
            JSONTokener jsonT = new JSONTokener(context);
            JSONObject jsonOBJ = (JSONObject) jsonT.nextValue();
            String code = jsonOBJ.optString("code");
            String message = jsonOBJ.optString("message");
            if (code.equals("N000000")) {
                JSONObject jsonobj = jsonOBJ.optJSONObject("data");
                JSONArray arr = jsonobj.optJSONArray("jsonObj");

                dealListBeans = new Gson().fromJson(arr.toString(), new
                        TypeToken<ArrayList<DealListBean>>() {
                        }.getType());
                dealListBeanLists.addAll(dealListBeans);
                if (pageIndex != 1) {
                    if (dealListBeans.size() != 0) {
                        dealListAdapter.notifyDataSetChanged();
                    } else {
                        refreshLayout.finishLoadMoreWithNoMoreData();
                    }
                } else {
                    dealListAdapter = new DealListAdapter(dealListBeanLists, this);
                    user_recycleview.setAdapter(dealListAdapter);
                }

            } else if (code.equals(Constants.STATUSTOKENERROR)) {
                // token过期
                if (!message.equals("null")) {
                    toast(message);
                }
            } else {
                if (!message.equals("null")) {
                    toast(message);
                }
            }
        } catch (JSONException ex) {
            Log.e("ShopListPost", "获取交易记录列表");
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    private class DealListAdapter extends RecyclerView.Adapter<DealListAdapter.ViewHolder> {

        private ArrayList<DealListBean> dealListBeanLists;
        private Context context;

        public DealListAdapter(ArrayList<DealListBean> dealListBeanLists, Context context) {
            this.dealListBeanLists = dealListBeanLists;
            this.context = context;
        }

        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
            View inflate = LayoutInflater.from(context).inflate(R.layout.lactivity_deallist_item, null);
            ViewHolder viewHolder = new ViewHolder(inflate);
            return viewHolder;
        }

        @Override
        public void onBindViewHolder(@NonNull ViewHolder viewHolder, int i) {
            final DealListBean dealListBean = dealListBeanLists.get(i);
            viewHolder.deallist_show.setText(dealListBean.getRemark());
            viewHolder.deallist_time.setText(dealListBean.getCreateTime());
            viewHolder.deallist_type.setText(dealListBean.getPayFromName());
            Glide.with(getActivity()).load(dealListBean.getShopLogo()).placeholder(R.drawable.zhanweitu_bg).into(viewHolder.deallist_image);
            viewHolder.deallist_price.setText(String.valueOf(dealListBean.getOrderMoney()));


        }


        @Override
        public int getItemCount() {
            return dealListBeanLists.size();
        }

        public class ViewHolder extends RecyclerView.ViewHolder {
            private ImageView deallist_image;
            private TextView deallist_show;
            private TextView deallist_type;
            private TextView deallist_time;
            private TextView deallist_price;

            public ViewHolder(@NonNull View itemView) {
                super(itemView);
                deallist_image = itemView.findViewById(R.id.deallist_image);
                deallist_show = itemView.findViewById(R.id.deallist_show);
                deallist_time = itemView.findViewById(R.id.deallist_time);
                deallist_price = itemView.findViewById(R.id.deallist_price);
                deallist_type = itemView.findViewById(R.id.deallist_type);
            }
        }
    }


}
